<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
		<el-tabs v-model="lang" @tab-change="handChange">
			<el-tab-pane v-for="(item, index) in languages.list" :key="index" :label="item.name" :name="item.symbol"
				lazy></el-tab-pane>
		</el-tabs>
            <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
				<el-form-item label="图片" prop="image">
				    <material-picker v-model="formData.image" />
					<div class="form-tips">
						<div>首页图片尺寸：750px*340px</div>
						<div>个人中心尺寸：750px*200px</div>
					</div>
				</el-form-item>
				<el-form-item label="外部图片链接" prop="image_ext">
				    <el-input v-model="formData.image_ext" clearable placeholder="请输入外部图片链接" />
					<div class="form-tips">有输入则显示外部图片</div>
				</el-form-item>
				<el-form-item label="显示位置" prop="loca">
				    <el-select class="flex-1" v-model="formData.loca" clearable placeholder="请选择位置">
				        <el-option 
				            v-for="(item, index) in dictData.swiper_loca"
				            :key="index" 
				            :label="item.name"
				            :value="parseInt(item.value)"
				        />
				    </el-select>
				</el-form-item>
                <el-form-item label="图片名称" prop="name">
                    <el-input v-model="formData.name" clearable placeholder="请输入图片名称" />
                </el-form-item>
                <el-form-item label="图片链接" prop="link">
                    <el-input v-model="formData.link" clearable placeholder="请输入图片链接" />
                </el-form-item>
                <el-form-item label="显示状态" prop="is_show">
                    <el-radio-group v-model="formData.is_show" placeholder="请选择显示状态">
                        <el-radio 
                            v-for="(item, index) in dictData.show_status"
                            :key="index"
                            :label="parseInt(item.value)"
                        >
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="formData.sort" clearable placeholder="请输入排序" />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="swiperEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiSwiperAdd, apiSwiperEdit, apiSwiperDetail } from '@/api/decoration'
import { apiLanguageAll } from '@/api/setting/language'
import { timeFormat } from '@/utils/util'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑轮播图片' : '新增轮播图片'
})

const languages = reactive({
		list: [{
			id: '',
			name: '',
			symbol: ''
		}],
		symbol: ''
	})
	
	const active = ref(0);
	const lang = ref("");
	const lang_1 = ref("");//切换前一个
	let langs = reactive([]);
	

// 表单数据
const formData = reactive({
    id: '',
    name: '',
    image: '',
	image_ext:'',
    link: '',
    loca: 1,
    is_show: 1,
    sort: 0,
    langs: []
})


// 表单验证
const formRules = reactive<any>({
    loca: [{
        required: true,
        message: '请选择位置',
        trigger: ['blur']
    }],
    is_show: [{
        required: true,
        message: '请选择显示状态',
        trigger: ['blur']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    
    langs = data['langs'];
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiSwiperDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
	
	//数组存储
	let arr = {
		'lang': lang.value,
		'image': formData.image,
		'image_ext': formData.image_ext,
	}
	
	//数组更新
	let array = pushArr(langs, lang.value, arr);
	langs = array;
	
	let langs_key = 0;
	Object.keys(langs).forEach((key) => {
		if (langs[key]['lang'] == languages.list[0]['symbol']) {
			langs_key = parseInt(key);
		}
	})
	
	//输入初始化
	let arr2 = langs[langs_key];
	Object.keys(arr2).forEach((key) => {
		//@ts-ignore
		formData[key] = arr2[key]
	})
	
	formData.langs = langs;
	
    const data = { ...formData,  }
    mode.value == 'edit' 
        ? await apiSwiperEdit(data) 
        : await apiSwiperAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}
const getData = async () => {
		const data = await apiLanguageAll()
		languages.list = data;
		languages.symbol = data[0]['symbol'];
		lang.value = languages.symbol;
	}
	//数组替换，存在替换，不存在追加
	const pushArr = (arr : any, lang : string, params : any) => {
		let result = false;
		Object.keys(arr).forEach((key) => {
			if (arr[key]['lang'] == lang) {
				arr[key] = params;
				result = true;
			}
		})
	
		if (!result) {
			arr.push(params);
		}
		return arr;
	}
	//标签切换
	const handChange = async (data : string) => {
		let lang_last = lang_1.value;
		lang_1.value = data
		const index = languages.list.findIndex((item) => item.symbol === data);
		active.value = index;
	
		//数组存储
		if (lang_last != "") {
			let arr = {
				'lang': lang_last,
				'image': formData.image,
				'image_ext': formData.image_ext,
			}
			let array = pushArr(langs, lang_last, arr);
			langs = array;
		}
		//输入初始化
		let arr2 = {
			'lang': "",
			'image': "",
			'image_ext': "",
		}
		Object.keys(langs).forEach((key) => {
			if (langs[key]['lang'] == data) {
				arr2 = langs[key];
			}
		})
	
		if (lang_last != "") {
			Object.keys(arr2).forEach((key) => {
				//@ts-ignore
				formData[key] = arr2[key]
			})
		}
	}



	defineExpose({
		open,
		setFormData,
		getDetail
	})
	
	getData()
</script>
